﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SCM.Common.Extensions;
using System;

namespace SCM.Common.Converter
{
    public class MicrosecondEpochConverter : DateTimeConverterBase
    {
        private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null && ((DateTime)value) > _epoch)
            {
                writer.WriteRawValue(UnitityHelper.GetTimeStamp((DateTime)value).ToString());
            }
            else
            {
                writer.WriteRawValue("0");
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null) { return null; }
            return UnitityHelper.TimeStampToDateTime((long)reader.Value);
        }
    }
    public class MicrosecondEpochToDateTimeConverter : DateTimeConverterBase
    {
        private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null && ((DateTime)value) > _epoch)
            {
                writer.WriteRawValue(string.Concat("\"", ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"), "\""));
            }
            else
            {
                writer.WriteRawValue("\"1970-01-01\"");
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null) { return null; }
            return DateTime.Parse(reader.Value.ToString());
        }
    }
}
